<template>
  <el-button v-bind="$attrs" :disabled="isStart" @click="handleStart" :loading="loading">
    {{ getButtonText }}
  </el-button>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, computed, unref, watchEffect } from 'vue'
import { useI18n } from 'vue-i18n'
import { useCountdown } from './useCountdown'
import { isFunction } from '@/utils/is'

export default defineComponent({
  name: 'CounttButton',
  props: {
    value: { type: [Object, Number, String, Array] },
    count: { type: Number, default: 60 },
    beforeStartFunc: {
      type: Function as PropType<() => Promise<boolean>>,
      default: null
    }
  },
  setup(props) {
    const { t } = useI18n()
    const loading = ref(false)

    const { currentCount, isStart, start, reset } = useCountdown(props.count)

    const getButtonText = computed(() => {
      return !unref(isStart)
        ? t('countdown.normalText')
        : t('countdown.sendText', [unref(currentCount)])
    })

    watchEffect(() => {
      props.value === undefined && reset()
    })

    /**
     * @description: 在执行前判断是否有外部函数，并决定执行后是否启动
     */
    async function handleStart() {
      const { beforeStartFunc } = props
      if (beforeStartFunc && isFunction(beforeStartFunc)) {
        loading.value = true
        try {
          const canStart = await beforeStartFunc()
          canStart && start()
        } finally {
          loading.value = false
        }
      } else {
        start()
      }
    }

    return { handleStart, currentCount, loading, getButtonText, isStart }
  }
})
</script>

<style scoped lang="scss"></style>
